package com.dbpediamobile;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class ConexionBusqueda {

		//tipo 1=simple, 0=avanzada
	public ArrayList<BusquedaResult> conectar(String query, int tipo) throws IOException {
		String u ="http://dbpedia.org/sparql?default-graph-uri=http://dbpedia.org&query="+query+"&format=text/xml&rt=Run+Query";
		
		URL dir = new URL(u);
        URLConnection yc = dir.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;

        String salida = "";
        while ((inputLine = in.readLine()) != null){
        	salida += inputLine;	
        }
          
        in.close();
		
        /* return salida */
        /* 0=busqueda avanzada, 1=busqueda simple*/
        if(tipo==0){
        	return this.Document2StringAvanzada(this.string2Document(salida));
        }
        if(tipo==1){
        	return this.Document2StringSimple(this.string2Document(salida));
        }
        return null;
        
	}
	
	public Document string2Document(String s)
	{ 
		Document tmpX=null; 
	    DocumentBuilder builder = null; 
	    int coderror;
		String msgerror;
		try{ 
	        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
	    }catch(javax.xml.parsers.ParserConfigurationException error){ 
	        coderror=10; 
	        msgerror="Error crando factory String2DOM "+error.getMessage(); 
	        return null; 
	    } 
	    try{ 
	        tmpX=builder.parse(new ByteArrayInputStream(s.getBytes())); 
	    }catch(org.xml.sax.SAXException error){ 
	        coderror=10; 
	        msgerror="Error parseo SAX String2DOM "+error.getMessage(); 
	        return null; 
	    }catch(IOException error){ 
	        coderror=10; 
	        msgerror="Error generando Bytes String2DOM "+error.getMessage(); 
	        return null; 
	    } 
	    return tmpX; 
	} 
	
	
	private ArrayList<BusquedaResult> Document2StringAvanzada(Document doc){
		
		NodeList listOfPersons = doc.getElementsByTagName("result"); 
		int totalPersons = listOfPersons.getLength();

		ArrayList<BusquedaResult> resultados = new ArrayList();
		
		String nodos = "";
		for(int s=0; s<listOfPersons.getLength() ; s++){

			Node firstPersonNode = listOfPersons.item(s);
			if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
				Element firstPersonElement = (Element)firstPersonNode; 
				
				NodeList firstNameList = firstPersonElement.getElementsByTagName("uri");
				Element firstNameElement = (Element)firstNameList.item(0);
				NodeList textFNList = firstNameElement.getChildNodes();
				
				BusquedaResult br = new BusquedaResult();
				
				br.url = ((Node)textFNList.item(0)).getNodeValue().trim();
				if(!br.url.contains("w3")){
				resultados.add(br);
				}
			}
		}
		return resultados;
	}
	
	private ArrayList<BusquedaResult> Document2StringSimple(Document doc){
		
		NodeList listOfPersons = doc.getElementsByTagName("row"); 
		int totalPersons = listOfPersons.getLength();
		
		ArrayList<BusquedaResult> resultados = new ArrayList();
		
		String nodos = "";
		for(int s=0; s<listOfPersons.getLength() ; s++){

			Node firstPersonNode = listOfPersons.item(s);
			if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
				Element firstPersonElement = (Element)firstPersonNode; 
				
				NodeList firstNameList = firstPersonElement.getElementsByTagName("column");
				Element firstNameElement = (Element)firstNameList.item(2);
				NodeList textFNList = firstNameElement.getChildNodes();
				
				NodeList firstNameList2 = firstPersonElement.getElementsByTagName("column");
				Element firstNameElement2 = (Element)firstNameList2.item(3);
				NodeList textFNList2 = firstNameElement2.getChildNodes();
				
				Element  firstNameElement3 = (Element)firstNameList2.item(4);
				NodeList textFNList3 = firstNameElement3.getChildNodes();
				
			
				
				//NodeList firstNameList3 = firstPersonElement.getElementsByTagName("span class");
				//NodeList textFNList3 = firstNameElement3.getChildNodes();
				
				BusquedaResult br = new BusquedaResult();
				
				br.url = ((Node)textFNList.item(0)).getNodeValue().trim();
				br.nombre = textFNList2.item(0).getNodeValue().toString();
				
				
				if(!br.url.contains("w3")){
					resultados.add(br);
					}
			}
		}
		return resultados;
	}
}
